<template>
  <div class="map-box" v-loading.body="listLoading" element-loading-text="Loading">
    <mainmap v-on:initmap="initmap"></mainmap>
    <transition name="slide">
      <div class="jiejing"  v-show="isShow">
        <div id="panorama" v-show="isJiejing"></div>
        <div class="nojiejing" v-show="!isJiejing">
          <img src="../../assets/no_jiejing.png">
        </div>
        <div class="close" @click="closeJiejing">
          <i class="el-icon-close"></i>
        </div>
      </div>
    </transition>
    <div class="mapOptionBtn">
      <el-button class="countinfo" @click="goback">返回监控</el-button>
      <el-button class="countinfo" @click="getDetail">刷新</el-button>
      <el-button class="countinfo" v-if="isSet" @click="setStart">设置起点</el-button>
      <el-button class="countinfo" v-else  @click="reSet">还原</el-button>
    </div>
  </div>
</template>

<script>
  import Mainmap from '@/components/Mainmap'
  import {wgs84togcj02,gcj02tobd09,formatTime} from '@/utils/index'
  import {getDetails} from '@/api/map'
  let polylines,startmarker;
    export default {
        name: "Follow",
        data (){
          return {
            map:null,
            listLoading:false,
            isShow:false,
            isJiejing:true,
            isSet:true,
            data:{}
          }
        },
      components:{
        Mainmap,
      },
      methods: {
        initmap(map) {
          this.map = map;
          this.getDetail();
        },
        getDetail(){
          let query={
            trackerId:this.$route.query.trackerId
          }
          this.listLoading = true
          getDetails(query).then( response => {
            if(response && response.body){
              this.data = response.body||{};
              this.setmarker(this.data);
            }
            this.listLoading = false
          })
        },
        goback(){
          this.$router.push({ path: '/monitor' })
        },
        setmarker(dataSource){
          let that=this;
          let geoc = new BMap.Geocoder();
          if(dataSource.lat){
            let pin1=wgs84togcj02(dataSource.lng,dataSource.lat);
            let newPonit1=gcj02tobd09(pin1[0],pin1[1]);
            let trackstr=`{trackerId:${dataSource.trackerId},number:'${dataSource.number||''}',imei:'${dataSource.imei}',userName:'${dataSource.userName||''}'}`;
            console.log(trackstr)
            that.map.setViewport([new BMap.Point(newPonit1[0],newPonit1[1])]);
            sessionStorage.getItem("preTrackerId")===dataSource.trackerId && sessionStorage.getItem("startPoint") &&  that.draw(new BMap.Point(JSON.parse(sessionStorage.getItem("startPoint")).lng,JSON.parse(sessionStorage.getItem("startPoint")).lat),new BMap.Point(newPonit1[0],newPonit1[1]))
            let newTime='';
            if(dataSource.syncTime) newTime=formatTime(new Date(dataSource.syncTime))
            let data_info = `
              <p class="device_details device_details_title"><a href='javascript:;' onclick="openDetials()">详情</a><a href='javascript:;' onclick="vista()">街景</a><a  href='javascript:;' onclick="linkTo(${trackstr})">轨迹</a></p>
              <p class="device_details"><span class="device_title" >车牌号:</span><span>${dataSource.number||''}</span> </p>
              <p class="device_details"><span class="device_title">状态:</span><span>${dataSource.signalStatus==0?'离线':dataSource.signalStatus==1?'在线':'休眠'}</span> </p>
              <p class="device_details"><span  class="device_title">速度:</span><span>${dataSource.speed>0?parseInt(dataSource.speed):0}km/h</span></p>
              <p class="device_details"><span class="device_title">通信信号:</span><span>${dataSource.rssi||''}</span> </p>
              <p class="device_details"><span class="device_title">GPS信号:</span><span>${dataSource.satellites||''}</span></p>
              <p class="device_details"><span class="device_title">最后上传时间:</span><span>${newTime}</span> </p>
              <p class="device_details"><span  class="device_title">IMEI号:</span><span>${dataSource.imei||''}</span> </p>
              <p class="device_details"><span class="device_title">使用人:</span><span>${dataSource.userName||''}</span> </p>
              <p class="device_details"><span  class="device_title">经纬度:</span><span>${dataSource.lng},${dataSource.lat}</span></p>
               `;
            var opts = {
              width : 300,     // 信息窗口宽度
              height: 270,     // 信息窗口高度
              title : "" , // 信息窗口标题
              enableCloseOnClick:false,
              enableMessage:true//设置允许信息窗发送短息
            };

            let myIcon = new BMap.Icon(require('../../assets/lat.png'), new BMap.Size(30,30));
            if(sessionStorage.getItem("preTrackerId")===dataSource.trackerId && sessionStorage.getItem("startPoint")) myIcon = new BMap.Icon(require('../../assets/ridingtrack/end.png'), new BMap.Size(32,70));
            let marker = new BMap.Marker(new BMap.Point(newPonit1[0],newPonit1[1]),{icon:myIcon});  // 创建标注
            let content =data_info;
            that.map.addOverlay(marker);               // 将标注添加到地图中

            /***获取地址* **/
            let addr='';
            geoc.getLocation(new BMap.Point(newPonit1[0],newPonit1[1]) , function(rs){
              if(rs){
                var addComp = rs.addressComponents;
                addr=(addComp.province  + addComp.city +  addComp.district +  addComp.street +  addComp.streetNumber);
                that.map.openInfoWindow(new BMap.InfoWindow(content+`<p class="device_details"><span class="device_title">位置：</span><span>${addr}</span></p>`,opts),new BMap.Point(newPonit1[0],newPonit1[1])); //开启信息窗口
              }else {
                addr=''
              }
            });

            addClickHandler(content,marker);
            function addClickHandler(content,marker){
              marker.addEventListener("click",function(e){
                openInfo(content,e)
              } );
            }
            function openInfo(content,e){
              var p = e.target;
              var point = new BMap.Point(p.getPosition().lng, p.getPosition().lat);
              let addr='';
              //获取地址
              geoc.getLocation(point , function(rs){
                if(rs){
                  var addComp = rs.addressComponents;
                  addr=(addComp.province  + addComp.city +  addComp.district +  addComp.street +  addComp.streetNumber);
                  var infoWindow = new BMap.InfoWindow(content+`<p class="device_details"><span class="device_title">位置：</span><span>${addr}</span></p>`,opts);  // 创建信息窗口对象
                  that.map.openInfoWindow(infoWindow,point); //开启信息窗口
                }else {
                  addr=''
                }
              });
            }
          }
        },
        /**@关闭街景*/
        closeJiejing(){
          this.isShow=false;
        },
        /***@检查是否支持flash*/
        flashChecker() {
          var hasFlash = 0;　　　　 //是否安装了flash
          var flashVersion = 0;　　 //flash版本

          if(document.all) {
            var swf = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
            if(swf) {
              hasFlash = 1;
              VSwf = swf.GetVariable("$version");
              flashVersion = parseInt(VSwf.split(" ")[1].split(",")[0]);
            }
          } else {
            if(navigator.plugins && navigator.plugins.length > 0) {
              var swf = navigator.plugins["Shockwave Flash"];
              if(swf) {
                hasFlash = 1;
                var words = swf.description.split(" ");
                for(var i = 0; i < words.length; ++i) {
                  if(isNaN(parseInt(words[i]))) continue;
                  flashVersion = parseInt(words[i]);
                }
              }
            }
          }
          return { f: hasFlash, v: flashVersion };
        },
        /**@展示街景**/
        showJiejing(){
          let fls = this.flashChecker();
          if(!fls.f) {
            window.location.href = "http://get.adobe.com/cn/flashplayer/";
          }else {
            let that=this;
            that.isShow=true;
            let pin=wgs84togcj02(that.data.lng,that.data.lat);
            let newPonit=gcj02tobd09(pin[0],pin[1]);
            let panoramaService = new BMap.PanoramaService();
            panoramaService.getPanoramaByLocation(new BMap.Point(newPonit[0],newPonit[1]), function(data){
              if (data == null) {
                that.isJiejing=false
              }else {
                that.isJiejing=true;
                let panorama = new BMap.Panorama('panorama');
                panorama.setPosition(new BMap.Point(newPonit[0],newPonit[1]));
              }
            });
          }
        },

        /***@设置起点* **/
        setStart(){
          let that=this;
          this.isSet=false;
          that.map.setDefaultCursor("crosshair");
          that.map.addEventListener("click",function(e){
            if(!that.isSet){
              startmarker &&  that.map.removeOverlay(startmarker);
              polylines &&  that.map.removeOverlay(polylines);
              let p=new BMap.Point(e.point.lng,e.point.lat);
              sessionStorage.setItem("startPoint", JSON.stringify(p));
              sessionStorage.setItem("preTrackerId",that.$route.query.trackerId);
              let pin1=wgs84togcj02(that.data.lng,that.data.lat);
              let newPonit1=gcj02tobd09(pin1[0],pin1[1]);
              let end=new BMap.Point(newPonit1[0],newPonit1[1]);
              that.draw(p,end)
            }
          });
        },
        /***@路线规划* **/
        draw(start,end){
          let that=this;
          let myIcon = new BMap.Icon(require('../../assets/ridingtrack/start.png'), new BMap.Size(32, 70));
          startmarker = new BMap.Marker(start,{icon:myIcon});  // 创建标注
          that.map.addOverlay(startmarker);
          let driving = new BMap.DrivingRoute(that.map);
          driving.search(start, end);
          driving.setSearchCompleteCallback(function(e) {
            let pts = driving.getResults().getPlan(0).getRoute(0).getPath();
            polylines &&  that.map.removeOverlay(polylines);
            polylines = new BMap.Polyline(pts,{strokeColor:'red', strokeWeight:6, strokeOpacity:0.8,strokeStyle:'solid'});
            that.map.addOverlay(polylines);
            that.map.setViewport(pts)
          })
        },
        /***@还原设置* **/
        reSet(){
          this.isSet=true;
          sessionStorage.removeItem("startPoint")
          this.map.clearOverlays()
          this.getDetail();
          this.map.setDefaultCursor("pointer");
        }
  },
  mounted(){
    let that=this;
    window.vista=function(){
      that.showJiejing()
    }

    window.linkTo=function(query){
      that.$router.push({path: '/monitor/track', query:query});
    }
  }
}
</script>

<style lang="scss" scoped>
  /*定义元素最终移动到的位置，以及移动到此位置需要的时间*/
  .slide-enter-active{
    transition: all .5s ease;
    -webkit-transition: all .5s ease;
    transform:translate3d(0,0,0);
    -webkit-transform:translate3d(0,0,0)
  }

  /*定义元素从什么位置离开，以及离开岛指定位置所需的时间*/
  .slide-leave-active{
    transition: all .5s ease;
    -webkit-transition: all .5s ease;
    transform:translate3d(0,0,0);
    -webkit-transform:translate3d(0,0,0)
  }
  /*定义元素从100%的位置移入到0，过渡结束后再从0回到100%的位置*/
  .slide-enter,.slide-leave-to{
    transform:translate3d(100%,0,0);
    -webkit-transform:translate3d(100%,0,0)
  }
  .map-box{
    height: 100%;
    position: relative;
  .jiejing{
    bottom: 3px;
    width: 50%;
    background: #f7f8fa;
    position: absolute;
    top: 0;
    right: 0;
    z-index: 10000;
  }
  }
  #panorama {
    width:100%; height: 100%;
  }
  .nojiejing{
    width:100%; height: 100%;
  img{
    margin-top: 20%;
    width: 60%;
    margin-left: 20%;
  }
  }
  .close{
    position: absolute;
    top: 10px;
    right: 10px;
    width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    background: rgba(255,255,255,.5);
    border: 1px solid #ccc;
    border-radius: 50%;
  }
</style>
